package src

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	. "github.com/soekchl/myUtils"
)

// 设置页面
func GetSet(c *gin.Context) {
	// 整个都是编辑页面 可折叠
	// 增加 和 删除 页面

	str := ""
	for k, v := range home.List {
		divId := fmt.Sprintf("div_%s_%v", v.Name, k)
		addColor := ""
		if v.SqlInfo != nil {
			addColor = `style="color: rgba(10,160,100)"`
		}
		head := fmt.Sprintf(setNewItem, v.Name, v.Path, divId)
		for kk, vv := range v.Title {
			// vv.Key 读取值
			id := fmt.Sprintf("%s_%v", divId, kk)
			head += fmt.Sprintf(addNewCol, id, vv.Name, vv.Key, divId, id)
		}
		if len(home.List)-k == 1 {
			str += fmt.Sprintf(addDetails, `open=""`, addColor, v.Name, k, divId, head)
		} else {
			str += fmt.Sprintf(addDetails, ``, addColor, v.Name, k, divId, head) // open=""
		}
	}

	// tb := fmt.Sprintf(tableHtml)
	showFallBack := ""
	if canFallBack() {
		showFallBack = `<input type="button" onclick="fallback()" value=" 撤销操作 ">`
	}
	c.Writer.Write([]byte(fmt.Sprintf(setHtml, showFallBack+str)))
	c.Writer.WriteHeader(http.StatusOK)
}

// 更新 home 列表
func PostSet(c *gin.Context) {
	tmp := &homeInfo{}
	err := c.ShouldBind(&tmp)
	if err != nil {
		Error(err)
		c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
		return
	}
	if len(tmp.List) < 1 {
		c.JSON(http.StatusBadRequest, gin.H{"msg": "不能为空"})
		return

	}

	// NOTE 同一个表中 不能有相同的列名
	m := make(map[string]bool)
	for k, v := range tmp.List {
		if m[v.Path] {
			c.JSON(http.StatusBadRequest, gin.H{"msg": fmt.Sprintf("第%v个路径 [%v] 重复", k+1, v.Path)})
			return
		} else {
			m[v.Path] = true
		}

		m := make(map[string]bool)
		for kk, vv := range v.Title {
			if m[vv.Key] {
				c.JSON(http.StatusBadRequest, gin.H{"msg": fmt.Sprintf("第%v个路径 第%v个关键字 [%v] 重复", k+1, kk+1, vv.Key)})
				return
			} else {
				m[vv.Key] = true
			}
		}
		if _, ok := homeMap[v.Path]; ok {
			tmp.List[k].SqlInfo = homeMap[v.Path].SqlInfo
		}
	}

	Info(ShowJsonFormat(tmp))
	home.List = tmp.List
	saveJson(home, homeDataFilename, true) // 更新保存
	c.JSON(http.StatusOK, gin.H{"message": "ok"})
}
